import React, { useState, useCallback, useEffect } from "react";
import { Card, Form, Input, Button, Checkbox, message } from "antd";
import { UserOutlined, LockOutlined } from "@ant-design/icons";
import { useNavigate } from "react-router-dom";
import { loginAsync } from "@/store/modules/authSlice";
import {
  usernameRules,
  passwordRules,
  codeRules,
} from "@/utils/validationRules";
import Captcha from "@/components/Captcha";
import { useSelector, useDispatch } from "react-redux";
import store  from "@/store";

const Login: React.FC = () => {
  const [form] = Form.useForm();
  const [rememberMe, setRememberMe] = useState(false);
  const [captchaCode, setCaptchaCode] = useState("");
  const navigate = useNavigate();
  const dispatch = useDispatch<typeof store.dispatch>();

  const { isLoading, error } = useSelector((state: ReturnType<typeof store.getState>) => state.authSlice);
  useEffect(() => {
    if (error) {
      message.error(error);
    }
  }, [error]);

  // 使用useCallback缓存onChange函数，避免频繁重新渲染
  const handleCaptchaChange = useCallback((code: string) => {
    setCaptchaCode(code);
  }, []);

  // 处理登录提交
  const handleSubmit = async(formData: Parameters<typeof loginAsync>[0]) => {
     try {
      await dispatch(loginAsync(formData)).unwrap();
      navigate("/");
     } catch (error) {
      console.log("登录失败", error);
     }
  };

  return (
    <div
      style={{
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
        height: "100vh",
        backgroundColor: "#f0f2f5",
        padding: "20px",
        overflow: "hidden",
        position: "fixed",
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        margin: 0,
      }}
    >
      <Card
        title={<div style={{ textAlign: "center" }}>欢迎登录</div>}
        style={{
          width: "100%",
          maxWidth: "400px",
          borderRadius: "8px",
          boxShadow: "0 4px 12px rgba(0, 0, 0, 0.1)",
        }}
      >
        <Form
          form={form}
          onFinish={handleSubmit}
          layout="vertical"
          initialValues={{
            username: "suixia",
            password: "Password@123",
            captcha: "",
          }}
        >
          <Form.Item name="username" rules={usernameRules} style={{ marginBottom: '44px' }}>
            <Input
              prefix={<UserOutlined className="site-form-item-icon" />}
              placeholder="请输入用户名"
              autoComplete="username"
            />
          </Form.Item>

          <Form.Item name="password" rules={passwordRules} style={{ marginBottom: '44px' }}>
            <Input
              prefix={<LockOutlined className="site-form-item-icon" />}
              type="password"
              placeholder="请输入密码"
              autoComplete="current-password"
            />
          </Form.Item>

          <Form.Item
            name="captcha"
            rules={codeRules}
            style={{ marginBottom: "30px", padding: 0 }}
          >
            <div
              style={{
                display: "flex",
                alignItems: "center",
                gap: "4px",
                height: "32px",
                padding: 0,
                margin: 0,
              }}
              id="captcha-container"
            >
              <Input
                placeholder="请输入验证码"
                style={{
                  flex: 1,
                  height: "32px",
                  padding: "4px 11px",
                  margin: 0,
                }}
              />
              <div
                style={{
                  height: "32px",
                  width: "100px",
                  padding: 0,
                  margin: 0,
                }}
              >
                <Captcha
                    length={4}
                    width={100}
                    height={32}
                    fontSize={18}
                    onChange={handleCaptchaChange}
                  />
              </div>
            </div>
          </Form.Item>

          <Form.Item>
            <Checkbox
              checked={rememberMe}
              onChange={(e) => setRememberMe(e.target.checked)}
            >
              记住我
            </Checkbox>
          </Form.Item>

          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              style={{ width: "100%", height: "40px", fontSize: "20px" }}
              loading={isLoading}
            >
              登录
            </Button>
          </Form.Item>
        </Form>

        <div
          style={{
            textAlign: "center",
            marginTop: "16px",
            fontSize: "14px",
            color: "#666",
          }}
        >
          <p>测试账号：</p>
          <p>• 商户: suixia / Password@123</p>
          <p>• 管理员: admin1 / Admin@123</p>
        </div>
      </Card>
    </div>
  );
};

export default Login;
